<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="handle-box">
          <div class="input-box">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入品种名称"
              class="input-with-select mr20"
              @keyup.enter.native="getList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
            <!--            <el-select v-model="searchForm.status" placeholder="请选择状态" class="mr20" clearable @change="getList">-->
            <!--              <el-option label="启用" :value="1"></el-option>-->
            <!--              <el-option label="禁用" :value="0"></el-option>-->
            <!--            </el-select>-->
            <!-- <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              class="mr20"
              @change="handleDateChange"
            ></el-date-picker> -->
          </div>
          <el-button type="primary" @click="handleAdd">添加品种</el-button>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="tableData.data" style="width: 100%" size="small" class="mt25">
        <el-table-column prop="id" label="ID" min-width="60" />
        <el-table-column prop="name" label="品种名称" min-width="120" />
        <el-table-column prop="category" label="作物种类" min-width="120" />
        <!--        <el-table-column prop="status" label="状态" min-width="80">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.status"-->
        <!--              :active-value="1"-->
        <!--              :inactive-value="0"-->
        <!--              active-color="#13ce66"-->
        <!--              inactive-color="#ff4949"-->
        <!--              @change="onChangeSeedStatus(scope.row)"-->
        <!--            ></el-switch>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column prop="admin_name" label="创建人" min-width="100" />-->
        <el-table-column prop="add_time" label="添加时间" min-width="150" />
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEditAttr(scope.row)"> 编辑属性 </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)"> 归档隐藏 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 40]"
          :page-size="searchForm.limit"
          :current-page="searchForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 添加品种弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <el-form ref="seedForm" :model="seedForm" :rules="rules" label-width="120px" class="seedForm">
        <el-form-item label="品种名称" prop="seed_name">
          <el-input v-model="seedForm.seed_name" placeholder="请输入品种名称" />
        </el-form-item>
        <el-form-item label="作物种类" prop="category">
          <el-select v-model="seedForm.category" placeholder="请选择作物种类" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSeed">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑品种属性弹窗 -->
    <el-dialog
      title="编辑品种属性"
      :visible.sync="attrDialogVisible"
      width="650px"
      :before-close="handleAttrDialogClose"
    >
      <div v-if="currentSeed" class="attr-dialog-content">
        <div class="attr-header">
          <el-form :inline="true" class="attr-form">
            <el-form-item label="项目">
              <el-select
                v-model="attrForm.name"
                placeholder="请选择或输入名称"
                style="width: 200px"
                filterable
                allow-create
                default-first-option
              >
                <el-option
                  v-for="item in attrNameOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-form :inline="true" class="attr-form">
            <el-form-item label="值">
              <el-input
                v-model="attrForm.val"
                placeholder="请输入属性值，如种子批次编码等"
                style="width: 350px"
              ></el-input>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addAttribute">添加属性</el-button>
        </div>

        <el-table :data="seedAttributes" style="width: 100%; margin-top: 20px">
          <el-table-column prop="name" label="名称" min-width="150"></el-table-column>
          <el-table-column prop="val" label="值" min-width="270"></el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="deleteAttribute(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 品种详情弹窗 -->
    <el-dialog title="品种详情" :visible.sync="detailVisible" width="700px">
      <div v-if="seedDetail" class="seed-detail">
        <div class="detail-item">
          <span class="label">ID:</span>
          <span class="value">{{ seedDetail.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">品种名称:</span>
          <span class="value">{{ seedDetail.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">显示名称:</span>
          <span class="value">{{ seedDetail.show_name }}</span>
        </div>
        <!--        <div class="detail-item">-->
        <!--          <span class="label">状态:</span>-->
        <!--          <span class="value">-->
        <!--            <el-tag :type="seedDetail.status === 1 ? 'success' : 'danger'">-->
        <!--              {{ seedDetail.status === 1 ? '启用' : '禁用' }}-->
        <!--            </el-tag>-->
        <!--          </span>-->
        <!--        </div>-->
        <div class="detail-item">
          <span class="label">创建人:</span>
          <span class="value">{{ seedDetail.admin_name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">添加时间:</span>
          <span class="value">{{ seedDetail.add_time }}</span>
        </div>

        <!-- 品种属性展示 -->
        <div v-if="seedAttributes && seedAttributes.length > 0">
          <h3 class="attr-title">品种属性</h3>
          <div v-for="attr in seedAttributes" :key="attr.id" class="detail-item">
            <span class="label">{{ attr.name }}:</span>
            <span class="value">{{ attr.val }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSeedList,
  addSeed,
  getSeedAttrList,
  getBaseConfig,
  addSeedAttr,
  deleteSeedAttr,
  deleteSeed,
  changeSeedStatus,
  getCategoryConfig,
} from '@/api/seed';
import { mapState } from 'vuex';

export default {
  name: 'SeedIndex',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: '',
        start_time: '',
        end_time: '',
      },
      dateRange: [],
      listLoading: false,
      tableData: {
        data: [],
        total: 0,
      },
      dialogVisible: false,
      attrDialogVisible: false,
      detailVisible: false,
      dialogTitle: '添加品种',
      seedForm: {
        seed_name: '',
        category: '',
      },
      attrForm: {
        name: '',
        val: '',
      },
      currentSeed: null,
      seedDetail: null,
      seedAttributes: [],
      attrNameOptions: [],
      categoryOptions: [],
      rules: {
        seed_name: [{ required: true, message: '请输入品种名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择作物种类', trigger: 'change' }],
      },
    };
  },
  computed: {
    ...mapState('app', ['pageLimit']),
  },
  mounted() {
    this.getList();
    this.getBaseConfig();
    this.getCategoryConfig();
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true;
      getSeedList(this.searchForm)
        .then((res) => {
          if (res.status === 200) {
            this.tableData.data = res.data.list || [];
            this.tableData.total = res.data.count || 0;
          } else {
            this.$message.error(res.msg || '获取数据失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取数据失败');
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 获取基础配置
    getBaseConfig() {
      getBaseConfig()
        .then((res) => {
          if (res.status === 200) {
            this.attrNameOptions = res.data || [];
          } else {
            this.$message.error(res.msg || '获取基础配置失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取基础配置失败');
        });
    },

    // 获取作物种类配置
    getCategoryConfig() {
      getCategoryConfig()
        .then((res) => {
          if (res.status === 200) {
            this.categoryOptions = res.data || [];
          } else {
            this.$message.error(res.msg || '获取作物种类配置失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取作物种类配置失败');
        });
    },

    // 日期范围变化
    handleDateChange(val) {
      if (val) {
        this.searchForm.start_time = val[0];
        this.searchForm.end_time = val[1];
      } else {
        this.searchForm.start_time = '';
        this.searchForm.end_time = '';
      }
      this.getList();
    },

    // 切换分页
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },

    // 切换每页显示条数
    handleSizeChange(val) {
      this.searchForm.limit = val;
      this.getList();
    },

    // 添加品种
    handleAdd() {
      this.dialogTitle = '添加品种';
      this.seedForm = {
        seed_name: '',
        category: '',
      };
      this.dialogVisible = true;
    },

    // 编辑品种属性
    handleEditAttr(row) {
      this.currentSeed = row;
      this.getSeedAttrList(row.id);
      this.attrDialogVisible = true;
    },

    // 获取品种属性列表
    getSeedAttrList(seedId) {
      getSeedAttrList(seedId)
        .then((res) => {
          if (res.status === 200) {
            this.seedAttributes = res.data || [];
          } else {
            this.$message.error(res.msg || '获取品种属性失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取品种属性失败');
        });
    },

    // 添加属性
    addAttribute() {
      if (!this.attrForm.name) {
        return this.$message.warning('请选择属性名称');
      }
      if (!this.attrForm.val) {
        return this.$message.warning('请输入属性值');
      }

      // 构建保存数据
      const data = {
        id: this.currentSeed.id,
        name: this.attrForm.name, // 直接传递属性名称，不传ID
        val: this.attrForm.val,
      };

      // 直接调用添加属性接口
      addSeedAttr(data)
        .then((res) => {
          if (res.status === 200) {
            this.$message.success('添加属性成功');
            // 清空输入
            this.attrForm.name = '';
            this.attrForm.val = '';
            // 刷新属性列表
            this.getSeedAttrList(this.currentSeed.id);
          } else {
            this.$message.error(res.msg || '添加属性失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '添加属性失败');
        });
    },

    // 删除属性
    deleteAttribute(row) {
      const index = this.seedAttributes.findIndex(
        (item) => item.id === row.id || (item.name === row.name && item.val === row.val),
      );

      if (index !== -1) {
        // 如果是已存在的属性(有id)，需要调用删除API
        if (row.id) {
          this.$confirm('确定要删除该属性吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              deleteSeedAttr(row.id)
                .then((res) => {
                  if (res.status === 200) {
                    this.$message.success('删除成功');
                    // 刷新属性列表
                    this.getSeedAttrList(this.currentSeed.id);
                  } else {
                    this.$message.error(res.msg || '删除失败');
                  }
                })
                .catch((err) => {
                  this.$message.error(err.msg || '删除失败');
                });
            })
            .catch(() => {});
        }
      }
    },

    // 查看品种详情
    handleViewDetail(row) {
      this.seedDetail = JSON.parse(JSON.stringify(row));
      this.getSeedAttrList(row.id);
      this.detailVisible = true;
    },

    // 提交品种表单
    submitSeed() {
      this.$refs.seedForm.validate((valid) => {
        if (valid) {
          addSeed(this.seedForm)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '添加失败');
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || '添加失败');
            });
        }
      });
    },

    // 删除品种
    handleDelete(row) {
      this.$confirm('确定要归档隐藏该品种吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用删除品种接口
          deleteSeed(row.id)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('归档隐藏成功');
                this.getList(); // 刷新列表
              } else {
                this.$message.error(res.msg || '归档隐藏失败');
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || '归档隐藏失败');
            });
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
    },

    // 修改品种状态
    onChangeSeedStatus(row) {
      changeSeedStatus(row.id, row.status)
        .then((res) => {
          if (res.status === 200) {
            this.$message.success('状态修改成功');
          } else {
            this.$message.error(res.msg || '状态修改失败');
            row.status = row.status === 0 ? 1 : 0; // 失败时恢复状态
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '状态修改失败');
          row.status = row.status === 0 ? 1 : 0; // 失败时恢复状态
        });
    },

    // 关闭弹窗
    handleClose() {
      this.$refs.seedForm.resetFields();
      this.dialogVisible = false;
    },

    // 关闭属性编辑弹窗
    handleAttrDialogClose() {
      this.attrDialogVisible = false;
      this.currentSeed = null;
      this.seedAttributes = [];
    },
  },
};
</script>

<style scoped lang="scss">
.input-with-select {
  width: 300px;
}

.handle-box {
  display: flex;
  justify-content: space-between;
}

.input-box {
  display: flex;
  align-items: center;
}

.mr20 {
  margin-right: 20px;
}

.mt25 {
  margin-top: 25px;
}

.block {
  margin-top: 20px;
  text-align: right;
}

.attr-dialog-content {
  .attr-header {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .attr-form {
    margin-bottom: 15px;
  }
}

.seed-detail {
  padding: 10px;

  .detail-item {
    margin-bottom: 15px;
    display: flex;

    .label {
      width: 120px;
      color: #606266;
      text-align: right;
      padding-right: 12px;
      font-weight: 500;
    }

    .value {
      flex: 1;
      color: #333;
    }
  }

  .attr-title {
    margin: 20px 0 10px;
    padding-left: 10px;
    border-left: 3px solid #409eff;
    font-size: 16px;
  }
}
</style>
